import { randomUUID } from "crypto";
import path from "path";

const url = require("url");

import qiniu from "qiniu";

export function uploadFile(config: Record<string, any>, file: string) {
  let access_key = config.access_key;
  let secret_key = config.secret_key;
  let bucket = config.bucket;
  let domain = config.domain;

  let localFile = file;
  if (/^".+"$/.test(localFile)) {
    localFile = file.substring(1, file.length - 1);
  }
  const ext = path.extname(localFile);
  //上传到七牛后保存的文件名
  const saveFile = "roubin/vscode/" + randomUUID() + ext;
  const mac = new qiniu.auth.digest.Mac(access_key, secret_key);
  const options = {
    scope: bucket + ":" + saveFile,
  };
  const putPolicy = new qiniu.rs.PutPolicy(options);
  const uploadToken = putPolicy.uploadToken(mac);

  const qiniuConfig = new qiniu.conf.Config();
  // 空间对应的区域，若不配置将自动查询
  qiniuConfig.regionsProvider = qiniu.httpc.Region.fromRegionId("z0");
  const formUploader = new qiniu.form_up.FormUploader(qiniuConfig);
  const putExtra = new qiniu.form_up.PutExtra();
  return new Promise<Record<string, any>>((resolve, reject) => {
    formUploader
      .putFile(uploadToken, saveFile, localFile, putExtra)
      .then(({ data, resp }) => {
        if (resp.statusCode === 200) {
          // 上传成功， 处理返回值
          resolve({
            name: path.basename(data.key, ext),
            url: url.resolve(domain, saveFile),
          });
        } else {
          reject();
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}
